using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Text;

namespace Nairo.Parser.Dom
{
	public static class TypeConverter
	{
		static Dictionary<string, Color> knownColors;
		
		public static void Initialize()
		{
			knownColors = new Dictionary<string, Color>();
			
			foreach (Color c in System.ComponentModel.TypeDescriptor.GetConverter(typeof (Color)).GetStandardValues()) {
				knownColors.Add(c.Name.ToLowerInvariant(), c);
			}
		}
		
		public static Color ConvertColor(string value, Color defaultValue)
		{
			try {
				return FromName(value);
			} catch (Exception) {
				try {
					return FromHexString(value);
				} catch (Exception) {
					return defaultValue;
				}
			}
		}
		
		public static Color FromHexString(string data)
		{
			if ((data.Length != 7) || (data[0] != '#'))
				throw new FormatException("'" + data + "' is not a valid hex color!");
			
			string hex = data.Substring(1);
			int red = 0, green = 0, blue = 0;
			
			try {
				red = Convert.ToInt32(hex.Substring(0, 2), 16);
				green = Convert.ToInt32(hex.Substring(2, 2), 16);
				blue = Convert.ToInt32(hex.Substring(4, 2), 16);
			} catch (FormatException) {
				throw new FormatException("'" + data + "' is not a valid hex color!");
			}
			
			return Color.FromArgb(red, green, blue);
		}
		
		public static Color FromName(string name)
		{
			if (knownColors.ContainsKey(name.ToLowerInvariant()))
				return Color.FromName(name);
			
			throw new FormatException("'" + name + "' not named color!");
		}
	}
}
